document.addEventListener('mouseup', function(event) {
    const selectedText = window.getSelection().toString().trim();

    if (selectedText.length > 0) {
        // 检查chrome.runtime是否定义，并且sendMessage是否是其属性
        if (chrome && chrome.runtime && typeof chrome.runtime.sendMessage === "function") {
            // 询问ChatGPT
            chrome.runtime.sendMessage({message: "text_selected", data: selectedText}, function(response) {
                if (chrome.runtime.lastError) {
                    console.error(chrome.runtime.lastError.message);
                    return;
                }

                if (!response || !response.answer) {
                    console.warn("Unexpected response from background:", response);
                }
            });
        } else {
            console.error("chrome.runtime or chrome.runtime.sendMessage is not defined. Is this running as a content script in a Chrome extension?");
        }
    }
});
